package mengrunsms

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	cmpp "github.com/bigwhite/gocmpp"
	"time"
)

const poolSize = 5

var pool = make(chan *cmpp.Client, poolSize)

const (
	connectTimeout time.Duration = time.Second * 3
)

var (
	uid          string = beego.AppConfig.DefaultString("mengrun.uid", "001359")
	pwd          string = beego.AppConfig.DefaultString("mengrun.pwd", "240596")
	initPoolSize        = 0
)

func init() {
	var err error
	for i := 0; i < 5; i++ {
		c := cmpp.NewClient(cmpp.V21)
		err = c.Connect("121.43.43.188:7890", uid, pwd, connectTimeout)
		if err != nil {
			logs.Error("mengrun sms service cannot be connected:%#v", err)
			continue
		}
		pool <- c
		initPoolSize++
	}
	logs.Info("mengrun sms service init %d num of client", initPoolSize)
}

func getClient() *cmpp.Client {
	var c *cmpp.Client
	if initPoolSize > 0 {
		c = <-pool
	}
	return c
}
func backClient(client *cmpp.Client) {
	if client == nil {
		return
	}
	pool <- client
}

func reconnect(c *cmpp.Client) error {
	return c.Connect("121.43.43.188:7890", uid, pwd, connectTimeout)
}
